package com.palm.vue.compiler.integration;

import com.palm.vue.compiler.VueManager;
import org.noear.solon.Solon;
import org.noear.solon.SolonApp;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.extend.staticfiles.StaticMimes;

import java.util.Date;

public class XPluginImp implements Plugin {
    private static final Date modified_time = new Date();
    static int maxAge = -1;

    public static int maxAge() {
        if (maxAge < 0) {
            if (Solon.cfg().isDebugMode()) {
                maxAge = 0;
            } else {
                maxAge = Solon.cfg().getInt("solon.staticfiles.maxAge", 600);
            }
        }
        return maxAge;
    }
    @Override
    public void start(SolonApp app) {
       //String mode= app.cfg().get("vue.mode","compile");
        int mode=app.cfg().getInt("vue.mode",1);
        boolean isStream=app.cfg().getBool("vue.use_bin",true);
        //debug模式直接响应内容
        if (mode==0||app.cfg().isDebugMode()) {
            StaticMimes.instance().putIfAbsent(".vue", "text/html");
        } else {//返回编译内容
            //编译等级

            VueManager.init(mode);
            app.add("**.vue", MethodType.GET, ctx -> {
                String path = ctx.path();
                byte[] out = VueManager.get(path);
                if (out == null) {
                    ctx.status(404);
                } else {
                    ctx.setHandled(true);
                    String modified_since = ctx.header("If-Modified-Since");
                    String modified_now = modified_time.toString();
                    if (modified_since != null && maxAge() > 0 && modified_since.equals(modified_now)) {
                        ctx.headerSet("Cache-Control", "max-age=" + maxAge());
                        ctx.headerSet("Last-Modified", modified_now);
                        ctx.status(304);
                    } else {

                        if (maxAge() > 0) {
                            ctx.headerSet("Cache-Control", "max-age=" + maxAge());
                            ctx.headerSet("Last-Modified", modified_time.toString());
                        }
                        if(isStream){
                            ctx.contentType("application/octet-stream");
                        }else{
                            ctx.contentType("text/javascript");
                            ctx.headerSet("Content-Encoding","gzip");
                        }
                        ctx.status(200);
                        ctx.output(out);
                    }
                }
            });
        }
    }
}
